﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.Services;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.Constants;
using Monkey.Warrenty.EntityModel;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web.WarrantyTickets
{
    public partial class Edit : System.Web.UI.Page
    {
        #region Properties

        private static WarrantyTicketBiz _warrantyTicketBiz;
        private static WarrantyTicketBiz WarrantyTicketManager
        {
            get { return _warrantyTicketBiz ?? (_warrantyTicketBiz = new WarrantyTicketBiz()); }
        }

        private static CustomerBiz _customerBiz;
        private static CustomerBiz CustomerManager
        {
            get { return _customerBiz ?? (_customerBiz = new CustomerBiz()); }
        }

        private int _ticketId;
        private int TicketId
        {
            get
            {
                if (_ticketId <= 0)
                    int.TryParse(Request.QueryString["id"], out _ticketId);
                return _ticketId;
            }
        }

        private WarrantyTicket _warrantyTicket;
        private WarrantyTicket CurrentTicket
        {
            get
            {
                if (_warrantyTicket == null && TicketId > 0)
                {
                    _warrantyTicket = WarrantyTicketManager.GetById(TicketId);
                }
                return _warrantyTicket;
            }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (WarrantyCommon.CurrrentEmployee == null)
            {
                Response.Redirect("~/Logon.aspx");
                return;
            }

            if (!WarrantyCommon.CurrrentEmployee.HasRole(RoleConstant.AdminBaoHanh))
            {
                Response.Redirect("~/NoPermission.aspx");
            }

            if (!Page.IsPostBack)
            {
                if (CurrentTicket == null)
                {
                    lblErrorMessage.Text = string.Format("{0}: Id={1}", Resources.GlobalStrings.NotExisted, TicketId);
                }
                else
                {
                    // common
                    txtCode.Text = CurrentTicket.Code;
                    txtReceivedDate.Text = string.Format("{0:dd/MM/yyyy}", CurrentTicket.CreatedDate);
                    txtDeliveryDate.Text = string.Format("{0:dd/MM/yyyy}", CurrentTicket.DeliveryDate);
                    txtContent.Text = CurrentTicket.TicketContent;
                    txtDescription.Text = CurrentTicket.Description;

                    // customer
                    var customer = CustomerManager.GetById(CurrentTicket.CustomerId);
                    if (customer != null)
                    {
                        txtName.Enabled = false; txtEmail.Enabled = false; txtAddress.Enabled = false; txtPhone.Enabled = false;
                        txtName.Text = customer.Name;
                        txtEmail.Text = customer.Email;
                        txtAddress.Text = customer.Address;
                        txtPhone.Text = customer.Phone;
                    }

                    // load employees
                    var employees = WarrantyTicketManager.GetEmployees();
                    ddlEmployees.DataSource = employees;
                    ddlEmployees.DataValueField = "Id";
                    ddlEmployees.DataTextField = "Name";
                    ddlEmployees.DataBind();
                    ddlEmployees.SelectedValue = CurrentTicket.CreatedEmployeeId.ToString(CultureInfo.InvariantCulture);

                    // received from
                    ddlReceivedFrom.SelectedValue = CurrentTicket.ReceivedFrom.ToString(CultureInfo.InvariantCulture);

                    // from employees
                    var fromEmployees = new List<Employee> { new Employee { Id = 0, Name = string.Empty } };
                    fromEmployees.AddRange(employees);
                    ddlFromEmployees.DataSource = fromEmployees;
                    ddlFromEmployees.DataValueField = "Id";
                    ddlFromEmployees.DataTextField = "Name";
                    ddlFromEmployees.DataBind();
                    if (CurrentTicket.EmployeeIdFrom != null)
                    {
                        ddlFromEmployees.SelectedValue = CurrentTicket.EmployeeIdFrom.Value.ToString(CultureInfo.InvariantCulture);
                    }

                    // load dealers
                    var dealers = WarrantyTicketManager.GetDealers();
                    dealers.Insert(0, new Dealer { Id = 0, Name = string.Empty });
                    ddlDealers.DataSource = dealers;
                    ddlDealers.DataValueField = "Id";
                    ddlDealers.DataTextField = "Name";
                    ddlDealers.DataBind();
                    if (CurrentTicket.DealerIdFrom != null)
                    {
                        ddlDealers.SelectedValue = CurrentTicket.DealerIdFrom.Value.ToString(CultureInfo.InvariantCulture);
                    }

                    // load states
                    var states = WarrantyTicketManager.GetTicketStates();
                    ddlTicketStatus.DataSource = states;
                    ddlTicketStatus.DataValueField = "Id";
                    ddlTicketStatus.DataTextField = "Name";
                    ddlTicketStatus.DataBind();
                    ddlTicketStatus.SelectedValue = CurrentTicket.StatusId.ToString(CultureInfo.InvariantCulture);
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            errorMessage.Visible = false;
            lblErrorMessage.Text = string.Empty;

            // validate inputs
            var code = txtCode.Text.Trim();
            if (code.Length == 0)
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.CodeIsRequired;
                return;
            }

            DateTime createdDate;
            if (!DateTime.TryParseExact(txtReceivedDate.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDate))
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }

            DateTime wishDate;
            if (!DateTime.TryParseExact(txtDeliveryDate.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out wishDate))
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.InvalidDate;
                return;
            }

            if (ddlEmployees.SelectedIndex < 0)
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.ReceivedEmployeeRequired;
                return;
            }

            var ticketContent = txtContent.Text.Trim();
            if (ticketContent.Length == 0)
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.TicketContentRequired;
                return;
            }

            CurrentTicket.CreatedDate = createdDate;
            CurrentTicket.CreatedEmployeeId = int.Parse(ddlEmployees.SelectedValue);
            CurrentTicket.TicketContent = ticketContent;
            CurrentTicket.DeliveryDate = wishDate;
            CurrentTicket.ReceivedFrom = int.Parse(ddlReceivedFrom.SelectedValue);
            CurrentTicket.Description = txtDescription.Text;

            switch (ddlReceivedFrom.SelectedValue)
            {
                case "1":
                    CurrentTicket.EmployeeIdFrom = null;
                    CurrentTicket.DealerIdFrom = null;
                    break;
                case "2":
                    CurrentTicket.EmployeeIdFrom = int.Parse(ddlFromEmployees.SelectedValue);
                    CurrentTicket.DealerIdFrom = null;
                    break;
                case "3":
                    CurrentTicket.DealerIdFrom = int.Parse(ddlDealers.SelectedValue);
                    CurrentTicket.EmployeeIdFrom = null;
                    break;
            }

            CurrentTicket.StatusId = int.Parse(ddlTicketStatus.SelectedValue);
            if (CurrentTicket.StatusId == 3) // completed
            {
                CurrentTicket.CompletedDate = DateTime.Now;
            }

            WarrantyTicketManager.UpdateTicket(CurrentTicket);

            errorMessage.Visible = true;
            lblErrorMessage.Text = Resources.GlobalStrings.UpdateSuccess;
        }

        #endregion

        #region Methods

        [WebMethod(EnableSession = true)]
        public static object TicketProductList(long ticketId)
        {
            var ticketProducts = WarrantyTicketManager.GetTicketProducts(ticketId);
            return new { Result = "OK", Records = ticketProducts };
        }

        [WebMethod(EnableSession = true)]
        public static object TicketDeleteProduct(int Id)
        {
            WarrantyTicketManager.DeleteTicketProduct(Id);
            return new { Result = "OK" };
        }

        [WebMethod(EnableSession = true)]
        public static object TicketLendProductList(long ticketId)
        {
            var ticketProducts = WarrantyTicketManager.GetTicketLendProducts(ticketId);
            return new { Result = "OK", Records = ticketProducts };
        }

        [WebMethod(EnableSession = true)]
        public static object TicketDeleteLendProduct(int Id)
        {
            WarrantyTicketManager.DeleteTicketLendProduct(Id);
            return new { Result = "OK" };
        }

        #endregion
    }
}